<template>
  <div v-loading="detailInfoShow">
    <div class="requestAdd">
      <!-- 审核按钮 -->
      <div class="search-button">
        <el-button
          v-if="pageType !== 'check'"
          class="btn submit"
          @click="handleAddSave(requestFormRef, 1)"
          ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
          >{{ "提交" }}</el-button
        >
        <el-button
          v-if="pageType !== 'check'"
          class="btn save"
          @click="handleAddSave(requestFormRef, 0)"
          ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
          >存为草稿</el-button
        >
        <el-button class="btn direction" @click="handleBack"
          ><el-icon class="icon" color="#fff"> <Back /> </el-icon
          >返回</el-button
        >
      </div>
      <!-- 内容区 -->
      <el-collapse v-model="activeNames">
        <!-- 基础信息 -->
        <el-collapse-item name="1" class="transform-down">
          <template #title>
            <span class="circle"></span>
            <span class="collapse-title">基础信息</span>
          </template>
          <div class="request-info">
            <el-form
              :model="requestForm"
              ref="requestFormRef"
              :rules="queryRules"
              label-width="120px"
              v-enterToNext
            >
              <el-row>
                <el-col :span="12">
                  <el-form-item label="项目名称：" prop="projectId">
                    <el-select
                      style="width: 100%"
                      v-model="requestForm.projectId"
                      placeholder="请选择"
                      clearable
                      filterable
                      class="search-input"
                      @change="handleProjectChange"
                    >
                      <el-option key="0" label="" value="" disabled>
                        <span style="float: left; color: #8492a6"
                          >项目编号</span
                        >
                        <span style="margin: 0 80px 0 130px; color: #8492a6"
                          >项目名称</span
                        >
                        <span
                          style="
                            margin: 0 0px 0 60px;
                            color: #8492a6;
                            font-size: 13px;
                          "
                          >项目类别</span
                        >
                        <span
                          style="float: right; color: #8492a6; font-size: 13px"
                          >项目类型</span
                        >
                      </el-option>
                      <el-option
                        v-for="item in projectList"
                        :key="item.projectId"
                        :label="item.projectName"
                        :value="item.projectId"
                      >
                        <span
                          style="float: left; color: #8492a6; width: 130px"
                          >{{ item.projectCode }}</span
                        >
                        <span
                          style="
                            display: inline-block;
                            margin: 0 10px 0 55px;
                             width: 200px
                            color: #8492a6;
                            white-space: nowrap;
                            overflow: hidden;
                            text-overflow: ellipsis;
                          "
                          :title="item.projectName"
                          >{{ item.projectName }}</span
                        >
                        <span
                          style="
                            float: right;
                            margin: 0 24px 0 0px;
                            font-size: 13px;
                          "
                        >
                          {{ item.projectTypeName }}
                        </span>
                        <span
                          style="
                            float: right;
                            margin: 0 132px 0 0px;
                            font-size: 13px;
                          "
                        >
                          {{ item.projectCategoryName }}
                        </span>
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12" v-if="requestForm.projectId">
                  <span
                    style="
                      line-height: 40px;
                      margin: 0 0px 0 40px;
                      font-size: 14px;
                      color: #0303ff;
                    "
                    >第 {{ needCount + 1 }}次发起本项目需求</span
                  >
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="需求类型：" prop="requirementTypes">
                    <el-checkbox-group
                      v-model="requestForm.requirementTypes"
                    >
                      <el-checkbox :label="0">
                        物资需求
                      </el-checkbox>
                      <el-checkbox :label="1">
                        研发需求
                      </el-checkbox>
                      <el-checkbox :label="2">
                        运维需求
                      </el-checkbox>
                    </el-checkbox-group>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label=" 需求描述：" prop="remark">
                    <el-input
                      :maxlength="500"
                      style="width: 100%"
                      v-model="requestForm.remark"
                      type="textarea"
                      :autosize="{ minRows: 3, maxRows: 4 }"
                      placeholder="请详细描述各类需求情况"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-collapse-item>
      </el-collapse>
      <!-- -----------关联项目信息---------- -->
      <div class="classacideydNeed" v-if="requestForm.projectId">
        <el-collapse v-model="activeNeeds">
          <div class="content">
            <div class="content-top">
              <div class="content-title">{{ projectForm.projectName }}</div>
              <div class="content-tab">
                <div v-if="projectForm.businessScheduleName" class="item-tab">
                  {{ projectForm.businessScheduleName }}
                </div>
                <!-- <div class="item-tab">回款进度</div> -->
                <div v-if="projectForm.projectStatusName" class="item-tab">
                  {{ projectForm.projectStatusName }}
                </div>
                <div v-if="projectForm.includeContractName" class="item-tab">
                  {{ projectForm.includeContractName }}
                </div>
                <!-- <img
                  src="/src/assets/images/Lament.png"
                  alt=""
                  style="width: 20px"
                /> -->
              </div>
            </div>
            <div class="content-bottom">
              <div class="item">
                <div class="title">项目编号：</div>
                <div class="text">{{ projectForm.projectCode }}</div>
              </div>
              <div class="item">
                <div class="title">项目执行地：</div>
                <div class="text">{{ projectForm.executiveAddress }}</div>
              </div>

              <div class="item">
                <div class="title">所属公司：</div>
                <div class="text">{{ projectForm.companyName }}</div>
              </div>
              <div class="item">
                <div class="title">业务人员：</div>
                <div class="text">{{ projectForm.businessName }}</div>
              </div>
            </div>
          </div>
          <!-- 基本信息 -->
          <el-collapse-item name="1" class="transform-down">
            <template #title>
              <span class="circle"></span>
              <span class="collapse-title">基本信息</span>
            </template>
            <div>
              <el-descriptions
                border
                style="margin: 20px 0"
                column="2"
                label-align="center"
                align="center"
              >
                <el-descriptions-item
                  label="项目类型"
                  label-class-name="desLabel"
                  label-align="center"
                  align="center"
                  >{{ projectForm.projectTypeName }}</el-descriptions-item
                >
                <el-descriptions-item
                  label="项目种类"
                  label-class-name="desLabel"
                  label-align="center"
                  align="center"
                  >{{ projectForm.projectCategoryName }}</el-descriptions-item
                >
                <el-descriptions-item
                  label="项目起止时间"
                  label-class-name="desLabel"
                  label-align="center"
                  align="center"
                  >{{ projectForm.startTime }} 至
                  {{ projectForm.endTime }}</el-descriptions-item
                >
                <el-descriptions-item
                  label="关联客户"
                  label-class-name="desLabel"
                  label-align="center"
                  align="center"
                  >{{ projectForm.customerName }}</el-descriptions-item
                >
                <el-descriptions-item
                  label="所属行业"
                  label-class-name="desLabel"
                  label-align="center"
                  align="center"
                  >{{ projectForm.industryName }}</el-descriptions-item
                >
                <el-descriptions-item
                  label="详细地址"
                  label-class-name="desLabel"
                  label-align="center"
                  align="center"
                  >{{ projectForm.address }}</el-descriptions-item
                >
                <el-descriptions-item
                  label="项目金额"
                  label-class-name="desLabel"
                  label-align="center"
                  align="center"
                  >{{
                    userStore.deptType == 5 ? projectForm.money : "****"
                  }}元</el-descriptions-item
                >
                <el-descriptions-item
                  label="是否签合同"
                  label-class-name="desLabel"
                  label-align="center"
                  align="center"
                  >{{ projectForm.includeContractName }}</el-descriptions-item
                >
                <el-descriptions-item
                  label="质保起止时间"
                  label-class-name="desLabel"
                  label-align="center"
                  align="center"
                  >{{ projectForm.warrantyStartTime }}</el-descriptions-item
                >
                <el-descriptions-item
                  label="质保终止时间"
                  label-class-name="desLabel"
                  label-align="center"
                  align="center"
                  >{{ projectForm.warrantyEndTime }}</el-descriptions-item
                >

                <el-descriptions-item
                  label="备注"
                  label-class-name="desLabel"
                  label-align="center"
                  align="center"
                  width="330px"
                >
                  <div class="desContent" :title="projectForm.remarks">
                    {{ projectForm.remarks || "--" }}
                  </div>
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </el-collapse-item>
          <!-- 甲方施工联系人 -->
          <el-collapse-item
            v-if="constructionData.length > 0"
            name="2"
            class="transform-down"
          >
            <template #title>
              <span class="circle"></span>
              <span class="collapse-title">甲方施工联系人</span>
            </template>
            <div class="contact-info">
              <el-table
                :data="constructionData"
                border
                height="180px"
                :header-cell-style="{ 'text-align': 'center' }"
              >
                <el-table-column
                  label="姓名"
                  prop="name"
                  :show-overflow-tooltip="true"
                  min-width="160"
                />
                <el-table-column
                  label="联系方式"
                  prop="phone"
                  :show-overflow-tooltip="true"
                  min-width="160"
                />
                <el-table-column
                  label="备注"
                  prop="remarks"
                  :show-overflow-tooltip="true"
                  min-width="200"
                />
              </el-table>
              <!-- 分页 -->
              <pagination
                class="pagination"
                :total="constructioTotal"
                v-model:page="construction.pageNum"
                v-model:limit="construction.pageSize"
                @pagination="getConstructionList"
              />
            </div>
          </el-collapse-item>
          <!-- 销售清单 -->
          <el-collapse-item
            v-if="salesListData.length > 0"
            name="3"
            class="transform-down"
          >
            <template #title>
              <span class="circle"></span>
              <span class="collapse-title">销售清单</span>
            </template>
            <div class="contact-info">
              <el-table
                :data="salesListData"
                border
                height="180px"
                :header-cell-style="{ 'text-align': 'center' }"
              >
                <!-- 操作模式 -->
                <!-- <el-table-column
                label="操作"
                align="center"
                :show-overflow-tooltip="true"
                width="100px"
              >
                <template #default="{ row, $index }">
                  <div class="table-operate">
                    <img
                      src="@/assets/icons/images/edit.png"
                      class="table-icon"
                      title="编辑"
                      @click="handleOperate('edit', row, $index)"
                    />
                    <img
                      src="@/assets/icons/images/delete.png"
                      class="table-icon"
                      title="删除"
                      @click="handleOperate('delete', row, $index)"
                    />
                  </div> </template
              ></el-table-column> -->
                <el-table-column
                  label="销售类目"
                  prop="saleCategoryName"
                  :show-overflow-tooltip="true"
                  min-width="160"
                />
                <el-table-column
                  label="设备品牌"
                  prop="brand"
                  :show-overflow-tooltip="true"
                  min-width="160"
                />
                <el-table-column
                  label="设备/平台名称"
                  prop="saleName"
                  :show-overflow-tooltip="true"
                  min-width="160"
                >
                  <template #default="scope">
                    {{ scope.row.saleName || "--" }}
                  </template>
                </el-table-column>
                <el-table-column
                  label="数量"
                  prop="quantity"
                  :show-overflow-tooltip="true"
                  min-width="160"
                />
                <el-table-column
                  label="技术参数"
                  prop="technologyParameter"
                  :show-overflow-tooltip="true"
                  min-width="160"
                />
              </el-table>
              <!-- 分页 -->
              <pagination
                class="pagination"
                :total="total"
                v-model:page="params.pageNum"
                v-model:limit="params.pageSize"
                @pagination="getSaleList"
              />
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
    </div>
  </div>
</template>

<script setup>
import useUserStore from "@/store/modules/user";
import { projectListRequest2 } from "@/api/purchase/request";
import {
  getRequirementCount,
  selectSaleByProjectId,
  getProjectGetInfo,
  selectPracticeInfosByProjectId,
  requirementGetInfo,
  getProjectGetInfoAdd,
  selectPracticeInfosByProjectIdAdd,
  selectSaleByProjectIdAdd,
  requirementAdd,
  requirementEdit,
  requirePullProject,
} from "@/api/sales/projectRequirements";
import { ElMessage, ElMessageBox } from "element-plus";
import { ref } from "vue";
const route = useRoute();
const emit = defineEmits([
  // 客户新增组件显隐
  "proRequirementsAddShow",
  // 更新客户新增组件显隐
  "update:proRequirementsAddShow",
  // 刷新父组件表格数据
  "refreshList",
]);
//当前用户信息
const userStore = useUserStore();
const props = defineProps({
  // 操作类型
  pageType: {
    type: String,
    default: "add",
  },
});
// 详情加载效果
const detailInfoShow = ref(false);
// 折叠栏默认展开
const activeNames = ref(["1"]);
const activeNeeds = ref(["1", "2", "3"]);
// 客户表单引用
const requestFormRef = ref();
const projectFormRef = ref();
// 客户表单数据模板
const requestFormTemplate = {
  projectId: null, //关联项目
  projectCategoryName: "", //项目类型
  remark: "", // 需求描述
  requirementTypes: [],
  type: 0, //按钮类型0：保存；1；提交
};
const data = reactive({
  // 客户表单
  requestForm: JSON.parse(JSON.stringify(requestFormTemplate)),
  //基本信息清单
  projectForm: {
    projectCode: "",
    executiveAddress: "",
    companyName: "",
    businessName: "",
    projectTypeName: "",
    projectCategoryName: "",
    startTime: "",
    endTime: "",
    customerName: "",
    industryName: "",
    address: "",
    money: "",
    includeContractName: "",
    warrantyStartTime: "",
    warrantyEndTime: "",
    remarks: "",
  },
  // 客户表单校验规则
  queryRules: {
    requirementTypes: [
      { required: true, message: "请选择", trigger: "change" },
    ],
    projectId: [
      { required: true, message: "请选择项目名称", trigger: "change" },
    ],
    remark: [
      { required: true, message: "请详细描述各类需求情况", trigger: "change" },
    ],
  },
  auditRemark: "", //审核备注
  auditResult: null, //审核类型
  applyId: null, //当前数据id
  endFlag: 0,
});
const {
  requestForm,
  projectForm,
  queryRules,
  auditRemark,
  auditResult,
  applyId,
  endFlag,
} = toRefs(data);
// 搜索参数
const params = reactive({
  pageNum: 1,
  pageSize: 50,
});
// 总数
const total = ref(0);
const construction = reactive({
  pageNum: 1,
  pageSize: 50,
});
// 总数
const constructioTotal = ref(0);
//施工联系人数据
const constructionData = ref([]);
//销售清单数据
const salesListData = ref([]);

// 项目名称列表
const projectList = ref([]);
//需求发起次数
const needCount = ref();
const loadingCheck = ref(false);

const pageType = ref(props.pageType);

/**
 * @description: 处理详情信息
 * @param {Number} id
 */
const handleDetailInfo = async (row) => {
  try {
    detailInfoShow.value = true;
    getNedCot(row.projectId);
    await requirementGetInfo({
      projectId: row.projectId,
      projectRequirementId: row.projectRequirementId,
    }).then((res) => {
      // console.log("详情数据", res);
      if (res.code == 200) {
        requestForm.value = { ...res.data.projectRequirementInfoRespVo };
        projectForm.value = res.data.projectInfoRespVo;
      }
    });
    await selectPracticeInfosByProjectId(
      { pageNum: construction.pageNum, pageSize: construction.pageSize },
      {
        projectId: row.projectId,
        projectRequirementId: row.projectRequirementId,
      }
    ).then((res) => {
      if (res.code == 200) {
        constructionData.value = res.rows;
        constructioTotal.value = res.total;
      }
    });
    let { pageNum, pageSize } = params;
    await selectSaleByProjectId(
      { pageNum, pageSize },
      {
        projectId: row.projectId,
        projectRequirementId: row.projectRequirementId,
      }
    ).then((res) => {
      if (res.code == 200) {
        salesListData.value = res.rows;
        total.value = res.total;
      }
    });
    detailInfoShow.value = false;
  } catch (error) {
    detailInfoShow.value = false;
  }
};
/**
 * @description: 保存
 * @param {Object} requestFormRef 客户表单引用
 */
const handleAddSave = async (requestFormRef, type) => {
  if (!requestFormRef) return;
  await requestFormRef.validate(async (valid, fields) => {
    if (valid) {
      ElMessageBox.confirm(
        "确定" + (type == 0 ? "存为草稿" : "提交") + "吗？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          confirmButtonClass: "confirmBtnClass",
          cancelButtonClass: "cancelBtnClass",
        }
      )
        .then(async () => {
          requestForm.value.type = type;
          let res;
          if (props.pageType === "add") {
            // 新增客户
            res = await requirementAdd(requestForm.value);
          } else {
            // 编辑客户
            res = await requirementEdit(requestForm.value);
          }
          if (res.code === 200) {
            emit("update:proRequirementsAddShow", false);
            emit("refreshList", false);
            ElMessage.success(res.msg);
            requestForm.value = JSON.parse(JSON.stringify(requestFormTemplate));
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
    }
  });
};

/**
 * @description: 处理项目选择
 * @param {Number} value 选择值
 */
const handleProjectChange = (value) => {
  if (value) {
    const selectedProject = projectList.value.find(
      (item) => item.projectId === value
    );
    if (selectedProject) {
      requestForm.value.projectCategoryName =
        selectedProject.projectCategoryName;
      requestForm.value.projectCode = selectedProject.projectCode;
    }
    getNedCot(value);
    getProInfo(value);
    getSaleList();
    getConstructionList();
  } else {
    requestForm.value.projectCategoryName = "";
    requestForm.value.projectCode = "";
    needCount.value = [];
    projectForm.value = [];
    salesListData.value = [];
  }
};
/**
 * @description: 发起项目需求次数
 * @param {Number} projectId 项目id
 */
const getNedCot = async (id) => {
  const res = await getRequirementCount(id);
  needCount.value = res.data;
};
/**
 * @description: 获取项目详细信息
 * @param {Number} projectId 项目id
 */
const getProInfo = async (id) => {
  const res = await getProjectGetInfoAdd(id);
  projectForm.value = res.projectInfoRespVo;
};
/**
 * @description: 获取销售清单列表
 */
const getSaleList = async () => {
  let { pageNum, pageSize } = params;
  const res = await selectSaleByProjectIdAdd(
    { pageNum, pageSize },
    { projectId: requestForm.value.projectId }
  );
  salesListData.value = res.rows;
  total.value = res.total;
};
/**
 * @description: 获取施工联系人列表
 */
const getConstructionList = async () => {
  let { pageNum, pageSize } = construction;
  const res = await selectPracticeInfosByProjectIdAdd(
    { pageNum, pageSize },
    { projectId: requestForm.value.projectId }
  );
  constructionData.value = res.rows;
  constructioTotal.value = res.total;
};

/**
 * @description: 返回
 */
const handleBack = () => {
  if (props.pageType === "detail" || props.pageType === "check") {
    emit("update:proRequirementsAddShow", false);
    requestForm.value = JSON.parse(JSON.stringify(requestFormTemplate));
  } else {
    ElMessageBox.confirm("确定返回上一级吗?以上数据未保存将会丢失!", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      confirmButtonClass: "confirmBtnClass",
      cancelButtonClass: "cancelBtnClass",
    })
      .then(async () => {
        emit("update:proRequirementsAddShow", false);
        requestForm.value = JSON.parse(JSON.stringify(requestFormTemplate));
      })
      .catch(() => {});
  }
};
/**
 * @description: 获取字典
 */
async function getDicts() {
  // 项目列表
  await requirePullProject({}).then((res) => {
    if (res) {
      projectList.value = res;
    }
  });
}
onMounted(() => {
  getDicts();
});
defineExpose({
  handleDetailInfo,
});
</script>

<style lang="scss" scoped>
.requestAdd {
  padding: 20px 20px;
  width: 100%;
  height: 100%;
  .request-info {
    padding: 20px 20px 5px 20px;
    background-color: #f0f0f0;
    // box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.1);
    margin: 10px 0;
  }

  .contact-info {
    padding-top: 20px;
  }

  :deep(.el-table) {
    th.el-table__cell {
      background: #f8f8f8 !important;
    }
  }

  :deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
    width: 268px !important;
    height: 34px !important;
  }

  .search-input {
    width: 268px;
    height: 34px;
  }

  .image-content {
    width: 100%;
    line-height: 0px;
    overflow: auto;
  }
  :deep(.pagination-container) {
    height: 56px;
  }
  .classacideydNeed {
    box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.1);
    padding: 20px 20px 5px 30px;
    margin-top: 10px;
  }
  .content {
    width: 1580px;
    height: 100px;
    background: #ffffff;

    padding: 0 0 0 20px;

    margin-bottom: 20px;
    .content-top {
      display: flex;
      align-items: center;
      .content-title {
        font-family: PingFang SC;
        font-weight: 500;
        font-size: 18px;
        color: #333333;
        line-height: 42px;
      }
      .content-tab {
        display: flex;
        align-items: center;

        .item-tab {
          padding: 3px 5px;
          margin: 0 10px;
        }
        .item-tab:nth-child(1) {
          color: rgba(87, 107, 249, 1);
          background-color: rgba(87, 107, 249, 0.2);
        }
        .item-tab:nth-child(2) {
          color: rgba(230, 122, 37, 1);
          background-color: rgba(230, 122, 37, 0.2);
        }
        .item-tab:nth-child(3) {
          color: rgba(63, 161, 122, 1);
          background-color: rgba(63, 161, 122, 0.2);
        }
        .item-tab:nth-child(4) {
          color: rgba(63, 161, 122, 1);
          background-color: rgba(63, 161, 122, 0.2);
        }
      }
    }
    .content-bottom {
      display: flex;
      margin: 30px 0;
      font-family: PingFang SC;
      font-weight: 400;
      font-size: 14px;
      color: #333333;
      .item {
        width: 20%;
        display: flex;
        align-items: center;
      }
    }
  }
  :deep(.desLabel) {
    // background: transparent !important;
    width: 200px;
    font-weight: 500 !important;
  }
  .desContent {
    // width: 100%;
    width: 330px;
    overflow: hidden;
    white-space: nowrap; /* 确保文本在一行内显示 */
    text-overflow: ellipsis; /* 使用省略号表示文字被截断 */
  }
}
</style>
